package com.cold.demo.web.util;

import org.springframework.util.Base64Utils;

import java.io.*;
import java.util.Base64;

public class Base64Util extends Base64Utils {


    /*
        Data URI scheme支持的类型有：
        data:,                          文本数据
        data:text/plain,                文本数据
        data:text/html,                 HTML代码
        data:text/html;base64,          base64编码的HTML代码
        data:text/css,                  CSS代码
        data:text/css;base64,           base64编码的CSS代码
        data:text/javascript,           Javascript代码
        data:text/javascript;base64,    base64编码的Javascript代码
        data:image/gif;base64,          base64编码的gif图片数据
        data:image/png;base64,          base64编码的png图片数据
        data:image/jpeg;base64,         base64编码的jpeg图片数据
        data:image/x-icon;base64,       base64编码的icon图片数据
     */


    /**
     * base64字符串转化为 inputStream
     * @param base64 不含头部的 base64 的字符串
     * @return
     */
    public static ByteArrayInputStream base64ToInputStream(String base64) {
        return new ByteArrayInputStream(Base64Utils.decodeFromString(base64));
    }

    /**
     * 返回不含 base64 头部的 base64 字符串
     */
    public static String fileToBase64(String path) {
        File file = new File(path);
        FileInputStream inputFile = null;
        try {
            inputFile = new FileInputStream(file);
            byte[] buffer = new byte[(int) file.length()];
            inputFile.read(buffer);
            return Base64.getEncoder().encodeToString(buffer);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }finally {
            close(inputFile);
        }
    }

    public static String inputStreamToBase64(InputStream inputStream){
        byte[] data = null;
        ByteArrayOutputStream os = null;
        try {
            os = new ByteArrayOutputStream();
            int arrayLength = 1024;
            byte[] buff = new byte[arrayLength];
            int len;
            while ((len = inputStream.read(buff, 0, arrayLength)) > 0) {
                os.write(buff, 0, len);
            }
            data = os.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(os);
            close(inputStream);
        }
        return Base64Utils.encodeToString(data);
    }




    private static void close(InputStream inputStream){
        if (inputStream!=null){
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void close(OutputStream outputStream){
        if (outputStream!=null){
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
